import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/page/Login/login'

import PhoneLogin from '@/page/Login/PhoneLogin'

import Home from '@/page/home'
import MyMusic from '@/page/MyMusic'
import Singer from '@/page/Singer'
import SongList from '@/page/SongList'
import Search from '@/page/Search'

Vue.use(VueRouter)


// 解决路由重复问题
//获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => {
    // err
    // 将报错的信息catch??
    console.log(err);
  })
}

const router = new VueRouter({
  routes: [
    {
      path: '/',
      name: 'Login',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'Login',
      component: Login,   // 直接引入
      children: [
        {
          name: 'UserLogin',
          path: 'UserLogin',
          component: () => import('@/page/Login/UserLogin')
        },
        {
          name: 'PhoneLogin',
          path: 'PhoneLogin',
          component: PhoneLogin
        }
      ]
    },

    // {
    //   path: '/index',
    //   name: 'index',
    //   component: () => import('@/page/main/index')
    // },
    {
      path: '/HomePageMain',
      name: 'HomePageMain',
      component: () => import('@/page/myhomepage/HomePageMain'),
      children: [
        {
          path: 'EditInformation',
          name: 'EditInformation',
          component: () => import('@/page/myhomepage/EditInformation')
        },
        {
          path: 'MySongList',
          name: 'MySongList',
          component: () => import('@/page/myhomepage/mysonglist/MySongList')
        },
        {
          path: '/',
          name: 'home',
          component: Home   // 直接引入
        },
        {
          path: '/my-music',
          name: 'my-music',
          component: MyMusic
        },
        {
          path: '/singer',
          name: 'singer',
          component: Singer
        },
        {
          path: '/song-list',
          name: '/song-list',
          component: SongList
        },
        {
          path: '/search',
          name: '/search',
          component: Search
        },
      ]
    },
  ]
})

export default router

// 路由前置守卫
//路由跳转前执行beforeEach中代码
router.beforeEach(function (to, from, next) {
  console.log(to)
  console.log("目标路由地址为:", to.fullPath);
  console.log("源路由地址为:", from.fullPath);

  let regex = /^[/]main.*$/; //
  if (regex.test(to.fullPath)) {
    //
    console.log("验证用户是否登录");

    let userInfo = window.sessionStorage.getItem("loginUserinfo");
    console.log("userinfo的信息为:", userInfo)

    // if (userInfo != null) {
    // let userInfoObj =  JSON.parse(userInfo);
    //解析成功后，应该再把用户名和密码传递给后端的Servlet，再次判断用户名和密码是否正确
    next();//放行。
    // } else {
    router.replace({path: '/login'});
    // }

  } else {
    next();//放行。
    console.log("不验证用户是否登录")
  }
});
